<template>
  <form @submit.prevent="handleSubmit">
      <table>
        <tbody>
          <tr>
            <td>标题</td>
            <td><input type="text"  v-model="formData.title"></td>
          </tr>
          <tr>
            <td>作者</td>
            <td><input type="text" v-model="formData.author"></td>
          </tr>
          <tr>
            <td>内容</td>
            <td><input type="text" v-model="formData.content"></td>
          </tr>
          <tr>
            <td>
              <button type="submit">保存</button>
              <RouterLink to="/"><button type="button">取消</button></RouterLink>
            </td>
          </tr>
        </tbody>
      </table>
    </form>
</template>
<!-- 组合式 -->
<script setup>
  import { ref, onMounted } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { useBlogStore } from '../stores/item.js'

const route = useRoute()
const router = useRouter()
const blogStore = useBlogStore()

// 表单初始化数据
const initFormData = () => ({
  id: null,
  title: '',
  author: '',
  content: ''
})

// 响应式表单数据
const formData = ref(initFormData())

// 判断是否为编辑模式
let isEditMode = ref(true)

// 初始化加载数据
onMounted(() => {
  if (route.params.id) {
    const blog = blogStore.blogs.find(b => b.id === Number(route.params.id))
    if (blog) {
      formData.value = { ...blog }
      isEditMode.value = true
    }
  }
})

// 提交处理
const handleSubmit = () => {
  console.log(isEditMode.value);
  console.log(formData.value.id);
  
  if (formData.value.id>0) {
    blogStore.updateBlog({ ...formData.value })
    console.log(2222);
    
  } else {
    console.log(1111);
    
    blogStore.addBlog({ ...formData.value })
  }
  router.push('/') // 返回列表页
}
</script>